package com.zzz.robot201.mvp.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hdl.udpsenderlib.UDPResult;
import com.hdl.udpsenderlib.UDPResultCallback;
import com.hdl.udpsenderlib.UDPSender;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.LogUtils;
import com.zzz.robot201.R;
import com.zzz.robot201.app.config.AppContent;
import com.zzz.robot201.di.component.DaggerMachineStatusComponent;
import com.zzz.robot201.mvp.contract.MachineStatusContract;
import com.zzz.robot201.mvp.presenter.MachineStatusPresenter;
import com.zzz.robot201.service.api.RobotUdpUtil;
import com.zzz.robot201.service.client.SendMsg;
import com.zzz.robot201.ui.RockerView;
import com.zzz.robot201.utils.SpUtils;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicInteger;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:机器状态
 * <p>
 * Created by MVPArmsTemplate on 07/09/2020 01:46
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class MachineStatusActivity extends BaseActivity<MachineStatusPresenter> implements MachineStatusContract.View {

    @BindView(R.id.btn_stand)
    Button btnStand;
    @BindView(R.id.btn_sit)
    Button btnSit;
    @BindView(R.id.btn_climb)
    Button btnClimb;
    @BindView(R.id.btn_go)
    Button btnGo;
    @BindView(R.id.btn_run)
    Button btnRun;
    @BindView(R.id.ll_action)
    LinearLayout llAction;
    @BindView(R.id.btn_back)
    Button btnBack;
    @BindView(R.id.iv_state_set)
    ImageView ivStateSet;
    @BindView(R.id.iv_state_test)
    ImageView ivStateTest;
    @BindView(R.id.iv_state_control)
    ImageView ivStateControl;
    @BindView(R.id.iv_state_data)
    ImageView ivStateData;
    @BindView(R.id.iv_state_d)
    ImageView ivStateD;
    @BindView(R.id.btn_x)
    Button btnX;
    @BindView(R.id.btn_b)
    Button btnB;
    @BindView(R.id.btn_y)
    Button btnY;
    @BindView(R.id.btn_a)
    Button btnA;
    @BindView(R.id.btn_up)
    Button btnUp;
    @BindView(R.id.btn_down)
    Button btnDown;
    @BindView(R.id.btn_left)
    Button btnLeft;
    @BindView(R.id.btn_right)
    Button btnRight;
    @BindView(R.id.tv_is_phone)
    TextView TvisPhone;
    float up = 0;
    float left = 0;
    byte unsigned_char_byte15_0 = 0;// byte[0] = 当前步态序号
    byte unsigned_char_byte15_4 = 13;// byte[4] = 当前状态序号
    float zx_speed = 0f;//转向速度
    @BindView(R.id.cv_up)
    View cvUp;
    @BindView(R.id.cv_left)
    View cvLeft;
    @BindView(R.id.cv_right)
    View cvRight;
    @BindView(R.id.cv_down)
    View cvDown;
    @BindView(R.id.rl_yg)
    RelativeLayout rlYg;
    @BindView(R.id.cv_r_left)
    View cvRLeft;
    @BindView(R.id.cv_r_right)
    View cvRRight;
    @BindView(R.id.btn_right_left)
    Button btnRightLeft;
    @BindView(R.id.btn_right_right)
    Button btnRightRight;
    @BindView(R.id.rl_right)
    RelativeLayout rlRight;

    @BindView(R.id.rocker_left)
    RockerView rockerViewLeft;

    @BindView(R.id.rocker_right)
    RockerView rockerViewRight;

    private boolean isphone;
    private Timer timer;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerMachineStatusComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    //    public static final int FLAG_HOMEKEY_DISPATCHED = 0x80000000; //需要自己定义标志
    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
//        this.getWindow().setFlags(FLAG_HOMEKEY_DISPATCHED, FLAG_HOMEKEY_DISPATCHED);//关键代码
        return R.layout.activity_machine_status; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        ButtonTouch btnliListener1 = new ButtonTouch();
        ButtonTouch btnliListener2 = new ButtonTouch();
        ButtonTouch btnliListener3 = new ButtonTouch();
        ButtonTouch btnliListener4 = new ButtonTouch();
        ButtonTouch btnliListener5 = new ButtonTouch();
        ButtonTouch btnliListener6 = new ButtonTouch();
        btnUp.setOnTouchListener(btnliListener1);
        btnDown.setOnTouchListener(btnliListener2);
        btnLeft.setOnTouchListener(btnliListener3);
        btnRight.setOnTouchListener(btnliListener4);
        btnRightRight.setOnTouchListener(btnliListener5);
        btnRightLeft.setOnTouchListener(btnliListener6);

        initRockerView();
    }

    private volatile AtomicInteger leftRockerViewLevel;
    private volatile RockerView.Direction leftDirection;
    private volatile AtomicInteger rightRockerViewLevel;
    private volatile RockerView.Direction rightDirection;
    private Timer mTimer;
    private Timer handShankLeftTimer;
    private Timer handShankRightTimer;

    private void initRockerView() {
        initTimer();
        //左摇杆
        leftRockerViewLevel = new AtomicInteger();
        leftDirection = RockerView.Direction.DIRECTION_CENTER;
        //点击中间回调
        rockerViewLeft.setOnClickRockerCenterListener(new RockerView.OnClickRockerCenterListener() {
            @Override
            public void onClickRocker() {
                left = 0;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                    }
                }).start();
                Log.i("YYYYYYYYYYYYY","点击左摇杆中间回调");
            }
        });
        //距离强度回调 0--100
        rockerViewLeft.setOnDistanceLevelListener(level -> {
            Log.i(TAG, "距离强度回调level: " + level);
            leftRockerViewLevel.set(level);
        });
        //方向回调，左摇杆支持上下两个方向
        rockerViewLeft.setOnShakeListener(RockerView.DirectionMode.DIRECTION_8, new RockerView.OnShakeListener() {
            @Override
            public void onStart() {
                Log.i(TAG, "左摇杆onStart");
            }

            @Override
            public void direction(RockerView.Direction direction) {
                Log.i(TAG, "左摇杆方向：" + direction);
                leftDirection = direction;
            }

            @Override
            public void onFinish() {
                left = 0;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                    }
                }).start();
                Log.i("YYYYYYYYYYYYY","左摇杆onFinish");
            }
        });


        //右摇杆
        rightRockerViewLevel = new AtomicInteger();
        rightDirection = RockerView.Direction.DIRECTION_CENTER;
        //点击中间回调
        rockerViewLeft.setOnClickRockerCenterListener(new RockerView.OnClickRockerCenterListener() {
            @Override
            public void onClickRocker() {
                zx_speed = 0;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                    }
                }).start();
            }
        });
        //距离强度回调 0--10
        rockerViewRight.setOnDistanceLevelListener(new RockerView.OnDistanceLevelListener() {
            @Override
            public void onDistanceLevel(int level) {
                rightRockerViewLevel.set(level);
            }
        });
        //方向回调，右摇杆支持2个方向,即左右
        rockerViewRight.setOnShakeListener(RockerView.DirectionMode.DIRECTION_8, new RockerView.OnShakeListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void direction(RockerView.Direction direction) {
                rightDirection = direction;

            }

            @Override
            public void onFinish() {
                zx_speed = 0;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                    }
                }).start();
            }
        });
    }

    private void initTimer() {
        mTimer = new Timer();
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                handleLeftRocker();
                handleRightRocker();

            }
        }, 0, 50);
    }

    private void unInitTimer() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer.purge();
            mTimer = null;
        }
    }

    private void handleRightRocker() {
        if (rightDirection == RockerView.Direction.DIRECTION_RIGHT) {
            Log.i("YYYYYYYYYYYYY", "Right Rocker Right Dir " + rightRockerViewLevel);
            Log.i("YYYYYYYYYYYYY","右摇杆右方向发送-----------------------------------");
            //右侧，右
            new Thread(new Runnable() {
                @Override
                public void run() {
                    sendUp(up, left, -rightRockerViewLevel.get(), unsigned_char_byte15_0, unsigned_char_byte15_4);
                }
            }).start();
        } else if (rightDirection == RockerView.Direction.DIRECTION_LEFT) {
            Log.i("YYYYYYYYYYYYY", "Right Rocker Left Dir " + rightRockerViewLevel);
            Log.i("YYYYYYYYYYYYY","右摇杆左方向发送-----------------------------------");
            //右侧，左
            new Thread(new Runnable() {
                @Override
                public void run() {
                    sendUp(up, left, rightRockerViewLevel.get(), unsigned_char_byte15_0, unsigned_char_byte15_4);
                }
            }).start();
        }
    }

    private void handleLeftRocker() {
        if (leftDirection == RockerView.Direction.DIRECTION_UP) {
            Log.i("YYYYYYYYYYYYY", "Left Rocker Up Dir " + leftRockerViewLevel);
            if (isphone) {
                up = 0f;
                //left = 0f;
                Log.i("YYYYYYYYYYYYY","左摇杆上方向发送-----------------------------------");
                Log.i("YYYYYYYYYYYYY",""+leftRockerViewLevel.get());
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        sendUp(up, leftRockerViewLevel.get(), zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                    }
                }).start();
            }


        } else if (leftDirection == RockerView.Direction.DIRECTION_DOWN) {
            Log.i("YYYYYYYYYYYYY", "Left Rocker Down Dir " + leftRockerViewLevel);
            //左侧，下
            if (isphone) {
                up = 0f;
                //left = 0f;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        sendUp(up, -leftRockerViewLevel.get(), zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                    }
                }).start();
            }
        }
    }

    //手柄左摇杆定时器
    private void initHandShankLeftTimer() {
        if (handShankLeftTimer == null ){
            handShankLeftTimer = new Timer();
            handShankLeftTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    Log.i("YYYYYYYYYYYYY","手柄左摇杆定时发送-发送值-----------------------------------");
                    Log.i("YYYYYYYYYYYYY",""+left);
                    //执行发送
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                        }
                    }).start();
                }
            }, 0, 50);
        }
    }
    //关闭手柄左摇杆定时器
    private void unInitHandShankLeftTimer() {
        if (handShankLeftTimer != null) {
            handShankLeftTimer.cancel();
            handShankLeftTimer.purge();
            handShankLeftTimer = null;
            Log.i("YYYYYYYYYYYYY","手柄左摇杆定时发送关闭定时器-----------------------------------");
            Log.i("YYYYYYYYYYYYY",""+left);
        }
    }

    //手柄右摇杆定时器
    private void initHandShankRightTimer() {
        if (handShankRightTimer == null ){
            handShankRightTimer = new Timer();
            handShankRightTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    Log.i("YYYYYYYYYYYYY","手柄右摇杆定时发送-发送值-----------------------------------");
                    Log.i("YYYYYYYYYYYYY",""+zx_speed);
                    //执行发送
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                        }
                    }).start();
                }
            }, 0, 50);
        }
    }
    //关闭手柄右摇杆定时器
    private void unInitHandShankRightTimer() {
        if (handShankRightTimer != null) {
            handShankRightTimer.cancel();
            handShankRightTimer.purge();
            handShankRightTimer = null;
            Log.i("YYYYYYYYYYYYY","手柄右摇杆定时发送关闭定时器-----------------------------------");
            Log.i("YYYYYYYYYYYYY",""+zx_speed);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unInitTimer();
    }


    @Override
    protected void onResume() {
        super.onResume();
        isphone = (boolean) SpUtils.get(MachineStatusActivity.this, AppContent.SaveInfoKey.ISPHONE, true);
        if (isphone) {
            TvisPhone.setText("手机模式");
        } else {
            TvisPhone.setText("手柄模式");
        }

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    @OnClick({R.id.btn_right_left, R.id.btn_right_right, R.id.btn_up, R.id.iv_state_d, R.id.iv_state_data, R.id.btn_down, R.id.btn_left, R.id.btn_right, R.id.btn_stand, R.id.btn_sit, R.id.btn_climb, R.id.btn_go, R.id.btn_run, R.id.btn_back, R.id.iv_state_set, R.id.iv_state_test, R.id.iv_state_control, R.id.btn_x, R.id.btn_b, R.id.btn_y, R.id.btn_a})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_stand:
                if (isphone) {
                    unsigned_char_byte15_4 = 15;
                    up = 0f;
                    left = 0f;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                        }
                    }).start();
                }

                break;
            case R.id.btn_sit:
                if (isphone) {
                    unsigned_char_byte15_4 = 8;
                    up = 0f;
                    left = 0f;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                        }
                    }).start();
                }

                break;
            case R.id.btn_climb:
                if (isphone) {
                    unsigned_char_byte15_4 = 17;
                    up = 0f;
                    left = 0f;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                        }
                    }).start();
                }

                break;
            case R.id.btn_go:
                if (isphone) {
                    unsigned_char_byte15_4 = 12;
                    up = 0f;
                    left = 0f;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                        }
                    }).start();
                }

                break;
            case R.id.btn_run:
                if (isphone) {
                    unsigned_char_byte15_4 = 14;
                    up = 0f;
                    left = 0f;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                        }
                    }).start();
                }

                break;
            case R.id.btn_back:


                killMyself();

                break;
            case R.id.iv_state_set:
                launchActivity(new Intent(this, SetActivity.class));
                break;
            case R.id.iv_state_test:

                break;
            case R.id.iv_state_control:
                break;

            case R.id.iv_state_d:
                startActivity(new Intent(this, Web3DActivity.class));
                break;
            case R.id.iv_state_data:
                startActivity(new Intent(this, MsgFeedbackActivity.class));
                break;
            case R.id.btn_x:
                if (isphone) {
                    unsigned_char_byte15_4 = 1;
                    up = 0f;
                    left = 0f;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                        }
                    }).start();
                }

                break;
            case R.id.btn_b:
                if (isphone) {
                    unsigned_char_byte15_4 = 2;
                    up = 0f;
                    left = 0f;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                        }
                    }).start();
                }

                break;
            case R.id.btn_y:
                if (isphone) {
                    unsigned_char_byte15_4 = 0;
                    up = 0f;
                    left = 0f;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                        }
                    }).start();
                }

                break;
            case R.id.btn_a:
                if (isphone) {
                    unsigned_char_byte15_4 = 3;
                    up = 0f;
                    left = 0f;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                        }
                    }).start();
                }

                break;
            case R.id.btn_up:
                //左侧，上
                if (isphone) {
                    up = 1f;
                    left = 0f;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                        }
                    }).start();
                }

                break;
            case R.id.btn_down:
                //左侧，下
                if (isphone) {
                    up = -1f;
                    left = 0f;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                        }
                    }).start();
                }

                break;
            case R.id.btn_left:
                //左侧，左
                if (isphone) {
                    up = 0f;
                    left = 1f;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                        }
                    }).start();
                }

                break;
            case R.id.btn_right:
                //左侧，右
                if (isphone) {
                    up = 0f;
                    left = -1f;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                        }
                    }).start();
                }

                break;

            case R.id.btn_right_left:
                //右侧，左
                zx_speed = 1;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                    }
                }).start();
                break;
            case R.id.btn_right_right:
                //右侧，右
                zx_speed = -1;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                    }
                }).start();
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.i("YYYYYYYYYYYYY","监听keycode:" + keyCode + "");
//        Log.i("YYYYYYYYYYYYY","监听keycode:" + event + "");
        if (keyCode == KeyEvent.KEYCODE_BUTTON_SELECT) {
            unsigned_char_byte15_4 = 2;
            unsigned_char_byte15_0 = 66;
            up = 0f;
            left = 0f;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                }
            }).start();
            return true;
        }

        if (keyCode == KeyEvent.KEYCODE_BUTTON_MODE) {
            isphone = (boolean) SpUtils.get(MachineStatusActivity.this, AppContent.SaveInfoKey.ISPHONE, true);
            if (isphone) {
                isphone = false;
                TvisPhone.setText("手柄模式");
                SpUtils.put(MachineStatusActivity.this, AppContent.SaveInfoKey.ISPHONE, false);
            } else {
                isphone = true;
                TvisPhone.setText("手机模式");
                SpUtils.put(MachineStatusActivity.this, AppContent.SaveInfoKey.ISPHONE, true);

            }
            return true;
        }
        if (keyCode == 100) {
            unsigned_char_byte15_4 = 0;
            up = 0f;
            left = 0f;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                }
            }).start();
        } else if (keyCode == 97) {
            unsigned_char_byte15_4 = 3;
//            unsigned_char_byte15_0 = 0;
            up = 0f;
            left = 0f;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                }
            }).start();
        } else if (keyCode == 102) {
            unsigned_char_byte15_4 = 7;
            up = 0f;
            left = 0f;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                }
            }).start();

        } else if (keyCode == 103) {
            unsigned_char_byte15_4 = 8;
            up = 0f;
            left = 0f;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                }
            }).start();
        } else if (keyCode == 108) {
            unsigned_char_byte15_4 = 2;
            unsigned_char_byte15_0 = 33;
            up = 0f;
            left = 0f;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                }
            }).start();
        }


        if (keyCode == 99) {
            unsigned_char_byte15_4 = 1;
            up = 0f;
            left = 0f;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                }
            }).start();
        } else if (keyCode == 96) {
            unsigned_char_byte15_4 = 2;
            unsigned_char_byte15_0 = 0;
            up = 0f;
            left = 0f;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                }
            }).start();
        }
        if (keyCode == 4 || keyCode == 67) {
            return false;
        }

        return true;
    }


    float y;
    float x;
    float z;
    float rz;
    float hat_x;
    float hat_y;
    float lt;
    float rt;
    boolean isLeft = false;
    boolean isRight = false;
    boolean isLt = false;
    boolean isRt = false;

    @Override
    public boolean onGenericMotionEvent(MotionEvent event) {
//        //左摇杆
//        Log.i("YYYYYYYYYYYYY",event.getAxisValue(MotionEvent.AXIS_X)+"::::====AXIS_X");
//        Log.i("YYYYYYYYYYYYY",event.getAxisValue(MotionEvent.AXIS_Y)+"::::====AXIS_Y");
//        //右摇杆
//        Log.i("YYYYYYYYYYYYY",event.getAxisValue(MotionEvent.AXIS_Z)+"::::====AXIS_Z");
//        Log.i("YYYYYYYYYYYYY",event.getAxisValue(MotionEvent.AXIS_RZ)+"::::====AXIS_RZ");
//        //十字方向键
//        Log.i("YYYYYYYYYYYYY","十字方向键");
//        Log.i("YYYYYYYYYYYYY",event.getAxisValue(MotionEvent.AXIS_HAT_X)+"::::====AXIS_HAT_X");
//        Log.i("YYYYYYYYYYYYY",event.getAxisValue(MotionEvent.AXIS_HAT_Y)+"::::====AXIS_HAT_Y");
        x = event.getAxisValue(MotionEvent.AXIS_X);
        y = event.getAxisValue(MotionEvent.AXIS_Y);
        z = event.getAxisValue(MotionEvent.AXIS_Z);
        rz = event.getAxisValue(MotionEvent.AXIS_RZ);
        hat_x = event.getAxisValue(MotionEvent.AXIS_HAT_X);
        hat_y = event.getAxisValue(MotionEvent.AXIS_HAT_Y);
        rt = event.getAxisValue(MotionEvent.AXIS_GAS);
        lt = event.getAxisValue(MotionEvent.AXIS_BRAKE);
        if (hat_x == -1.0) {
            unsigned_char_byte15_4 = 12;
            up = 0f;
            left = 0f;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                }
            }).start();
        } else if (hat_x == 1.0) {
            unsigned_char_byte15_4 = 14;
            up = 0f;
            left = 0f;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                }
            }).start();
        } else if (hat_y == -1.0) {
            unsigned_char_byte15_4 = 15;
            up = 0f;
            left = 0f;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                }
            }).start();
        } else if (hat_y == 1.0) {
            unsigned_char_byte15_4 = 13;
            up = 0f;
            left = 0f;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                }
            }).start();
        }

        if (lt > 0) {
            isLt = true;
            left = lt * 100;
            int s = (int) left;
            up = s;
            left = 0f;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                }
            }).start();
        }
        if (isLt) {
            if (lt == 0) {
                isLt = false;
                up = 0;
                left = 0f;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                    }
                }).start();
            }
        }

        if (rt > 0) {
            isRt = true;
            left = rt * 100;
            int s = (int) left;
            up = -s;
            left = 0f;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                }
            }).start();
        }

        if (isRt) {
            if (rt == 0) {
                isRt = false;
                up = 0;
                left = 0f;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                    }
                }).start();
            }
        }
        Log.i("YYYYYYYYYYYYY",x + "^^^^" + y + "***" + z + "&&&" + rz);


        if (x - y > 0 && x + y < 0) {
            isLeft = true;
            up = y * 100;
            int s = (int) up;
            s = Math.abs(s);
            left = s;
            up = 0f;
            initHandShankLeftTimer();

        } else if (x - y < 0 && x + y > 0) {
            isLeft = true;
            up = y * 100;
            int s = (int) up;
            s = -s;
            left = s;
            up = 0f;
            initHandShankLeftTimer();
//            new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
//                }
//            }).start();
        }
        if (isLeft) {
            if (x == 0 && y == 0) {
                isLeft = false;
                left = 0;
                Log.i("YYYYYYYYYYYYY","手柄左摇杆归中心点为0-----------------------------------");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                    }
                }).start();
                unInitHandShankLeftTimer();
            }
        }


        if (z - rz < 0 && z + rz < 0) {
            isRight = true;
            zx_speed = -z;
            zx_speed = zx_speed * 100;
            int s = (int) zx_speed;
            zx_speed = s;
            left = 0f;
            initHandShankRightTimer();
        } else if (z - rz > 0 && z + rz > 0) {
            isRight = true;
            zx_speed = z * 100;
            int s = (int) zx_speed;
//            s = Math.abs(s);
            zx_speed = -s;
            left = 0f;
            initHandShankRightTimer();
        }
        if (isRight) {
            if (z == 0 && rz == 0) {
                isRight = false;
                zx_speed = 0;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        sendUp(up, left, zx_speed, unsigned_char_byte15_0, unsigned_char_byte15_4);
                    }
                }).start();
                unInitHandShankRightTimer();
            }
        }

        return true;
    }

    private static String robotHost;
    private static int robotPort;


    private void sendUp(float up, float left, float zx, byte unsigned_0, byte unsigned_4) {
        robotHost = (String) SpUtils.get(MachineStatusActivity.this, AppContent.SaveInfoKey.DEVICEIP, "");
        robotPort = (int) SpUtils.get(MachineStatusActivity.this, AppContent.SaveInfoKey.DEVICEPORT, 1);
        RobotUdpUtil udp = new RobotUdpUtil();
        int test = 0;
        if (test == 0) {// 发起通信
            long[] unsigned_long_long = new long[]{0, 0};//时间，暂时都设为0;
            float[] float3 = new float[]{left, up, zx};// 顺序为x方向速度,y方向速度,转向速度
            float[] float2 = new float[]{0f, 0f};// 固定 0,0

            SendMsg sendMsg = new SendMsg(robotHost, robotPort, unsigned_long_long[0], unsigned_long_long[1])
                    .setFloat3(float3).setFloat2(float2)
                    .setUnsigned_char_byte15_0(unsigned_0)
                    .setUnsigned_char_byte15_4(unsigned_4)
                    .checkBuf();
            sendMsg(sendMsg);
        } else {
            // 接收通信
//            receiveMsg();
            udp.receiveMsg("00000001", 43795);
        }
    }


    DatagramSocket ds = null;

    private boolean sendMsg(SendMsg sendMsg) {
        boolean result = false;
        try {
            ds = new DatagramSocket();
            byte[] data = sendMsg.getbuf();
//            UDPSender.getInstance()
//                    .setInstructions(data)//设置发送的指令[可为空]
//                    .setReceiveTimeOut(70 * 1000)//设置接收超时时间[可不写，默认为60s]--超时70s就停止任务
//                    .setTargetPort(sendMsg.getServerPort())//设置发送的端口[必写]
////                    .setLocalReceivePort()//设置本机接收的端口[可不写，默认为目标端口]
//                    .setTargetIp(sendMsg.getServerHost())//设置目标ip地址，[可不写，默认广播]
//                    .schedule(2, 1000)//执行2次，间隔三秒执行（上一次结束到下一次开始的时间）
//                    .start(new UDPResultCallback() {
//
//                        @Override
//                        public void onStart() {
//                            //请求开始的时候回调
//                        }
//
//                        @Override
//                        public void onNext(UDPResult result) {
//                            //每收到一个结果的时候就回调
//                        }
//
//                        @Override
//                        public void onCompleted() {
//                            //请求结束的时候回调
//                        }
//
//                        @Override
//                        public void onError(Throwable throwable) {
//                            //当发生错误的时候回调
//                        }
//                    });


            DatagramPacket dp = new DatagramPacket(data, data.length,
                    InetAddress.getByName(sendMsg.getServerHost()),
                    sendMsg.getServerPort());
            ds.send(dp);
            result = true;
            Log.i("YYYYYYYYYYYYY","发送：" + result);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ds != null) {
                ds.close();
            }
            return result;
        }
    }


    private void receiveMsg() {
        UDPSender.getInstance()
                .setLocalReceivePort(43795)//接收端口
                //.schedule(2, 80)//执行2次，间隔三秒执行（上一次结束到下一次开始的时间）
                .start(new UDPResultCallback() {
                    @Override
                    public void onStart() {
                        LogUtils.debugInfo("开始了");
                    }

                    @Override
                    public void onNext(UDPResult result) {
                        LogUtils.debugInfo("收到结果" + "result");
//                        ResponseMsg responseMsg = ResponseMsg.getResponseMsg(result.getResultData());
//                        LogUtils.debugInfo(responseMsg.toString());
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        LogUtils.debugInfo("出错" + throwable);
                    }

                    @Override
                    public void onCompleted() {
                        LogUtils.debugInfo("完成");
                    }
                });
    }


    class ButtonTouch implements View.OnTouchListener {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (v.getId() == R.id.btn_up) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    cvUp.setVisibility(View.GONE);
                }
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    cvUp.setVisibility(View.VISIBLE);
                }
            } else if (v.getId() == R.id.btn_down) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    cvDown.setVisibility(View.GONE);
                }
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    cvDown.setVisibility(View.VISIBLE);
                }
            } else if (v.getId() == R.id.btn_left) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    cvLeft.setVisibility(View.GONE);
                }
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    cvLeft.setVisibility(View.VISIBLE);
                }
            } else if (v.getId() == R.id.btn_right) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    cvRight.setVisibility(View.GONE);
                }
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    cvRight.setVisibility(View.VISIBLE);
                }
            } else if (v.getId() == R.id.btn_right_right) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    cvRRight.setVisibility(View.GONE);
                }
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    cvRRight.setVisibility(View.VISIBLE);
                }
            } else if (v.getId() == R.id.btn_right_left) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    cvRLeft.setVisibility(View.GONE);
                }
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    cvRLeft.setVisibility(View.VISIBLE);
                }
            }
            return false;
        }
    }
}
